package top.wshape1.rpc.provider.handler;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import top.wshape1.rpc.common.constant.ChannelConstant;
import top.wshape1.rpc.message.PingPongMessage;

/**
 * @author Wshape1
 * @version 1.0
 * @description
 * @since 2024-02-07
 */

@Slf4j
@ChannelHandler.Sharable
public class ProviderIdleHandler extends ChannelDuplexHandler {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        if (evt instanceof IdleStateEvent) {
            if (((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {
                // 每READER_IDLE_TIME s内没有收到Ping 会触发一次此事件
                log.info("No Ping from the consumer is received for {}ms. The connection is about to be closed. " +
                                "consumer address: '{}'",
                        ChannelConstant.IDLE_READER_TIME,
                        ctx.channel().remoteAddress());
                ctx.close();
            }
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof PingPongMessage))
            super.channelRead(ctx, msg);
    }
}
